package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
@Value("${reggie.path}")
    private String baseDir;

    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file){

        File dir = new File(baseDir);
        if(!dir.exists()){
            dir.mkdir();
        }
        //获取上传文件的名字
        String originalFilename = file.getOriginalFilename();
        //获取扩展名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成文件名
        String fileName = UUID.randomUUID() + extName;
        //写入磁盘
        try {
            file.transferTo(new File(dir,fileName));
        } catch (IOException e) {
           throw new SystemException("服务器写入磁盘文件失败",e);
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //获取上传图片地址
        //完整路径
        String filePath = baseDir+"/"+name;
        //获取输入字节流
        FileInputStream inputStream =null;
        try {
            inputStream =new FileInputStream(filePath);
            IOUtils.copy(inputStream,response.getOutputStream());
        } catch (IOException e) {
           throw new SystemException("获取文件失败",e);
        }

    }

}
